package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description:
 * @Author: Hank
 * @Date: 2025/3/3 18:09
 */
@Slf4j
@RestControllerAdvice//声明为全局异常处理器
public class GlobalExceotionHandler {
    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("程序出错啦", e);
        return Result.error("出错啦请联系管理员");
    }
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error("程序出错啦", e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg =message.substring(i);
        String[] arr = errMsg.split(" ");
        return Result.error("用户名重复："+arr[2]);
    }

}
